package onvifprotocol

import (
	"errors"
	"fmt"
	"github.com/beevik/etree"
	imaging "github.com/use-go/onvif/Imaging"
	"github.com/use-go/onvif/media"
	"github.com/use-go/onvif/xsd"
	"github.com/use-go/onvif/xsd/onvif"
	"iot-base/common/logger"
	imaging2 "main/onvifprotocol/imaging"
)

func (m *CameraDevice) FocusMove(data map[string]interface{}) error {
	var result []byte
	var err error
	switch data["Type"].(string) {
	case "Relative":
		focusMove := imaging2.RelativeMove{
			VideoSourceToken: onvif.ReferenceToken(data["VideoSourceToken"].(string)),
		}
		focusMove.Focus.Relative.Distance = xsd.Float(data["Position"].(float64))
		focusMove.Focus.Relative.Speed = xsd.Float(data["Speed"].(float64))
		result, err = m.CallMethod(focusMove)
	case "Absolute":
		focusMove := imaging2.AbsoluteMove{
			VideoSourceToken: onvif.ReferenceToken(data["VideoSourceToken"].(string)),
		}
		focusMove.Focus.Absolute.Position = xsd.Float(data["Position"].(float64))
		focusMove.Focus.Absolute.Speed = xsd.Float(data["Speed"].(float64))
		result, err = m.CallMethod(focusMove)
	case "Continuous":
		focusMove := imaging2.ContinuousMove{
			VideoSourceToken: onvif.ReferenceToken(data["VideoSourceToken"].(string)),
		}
		focusMove.Focus.Continuous.Speed = xsd.Float(data["Speed"].(float64))
		result, err = m.CallMethod(focusMove)
	}
	if err != nil {
		return err
	}
	logger.Log.Info("FocusMove xml resp:" + string(result))
	doc := etree.NewDocument()
	err = doc.ReadFromBytes(result)
	if err != nil {
		return err
	}
	fault := doc.FindElements("./Envelope/Body/Fault/Reason/Text")
	if len(fault) > 0 {
		return errors.New(fault[0].Text())
	}
	return nil
}

func (m *CameraDevice) GetMoveOptions(data map[string]interface{}) (map[string]interface{}, error) {
	resp := make(map[string]interface{})

	focusMove := imaging.GetMoveOptions{
		VideoSourceToken: "00000",
	}
	result, err := m.CallMethod(focusMove)
	fmt.Println("err", err)
	fmt.Println(string(result))
	return resp, nil
}

func (m *CameraDevice) GetStreamUri() {
	data := media.GetStreamUri{
		ProfileToken: "MediaProfile00000",
	}
	result, err := m.CallMethod(data)
	fmt.Println("err", err)
	fmt.Println(string(result))
	return
}
